//
//  NDCustomAlert.m
//  PDF
//
//  Created by 刘星辰 on 2017/3/29.
//  Copyright © 2017年 刘星辰. All rights reserved.
//

#import "CustomAlert.h"
#import "LGImageManagerIO.h"

const CGFloat customAlertfaultWidth = 270.0f;

@interface CustomAlert()
{
    CGRect _frame;
    UIView *_blankNDSemicircleView;
    NSTimer *_timer;
    
    NSTimeInterval _keyboardAnimationDuration;
    UIViewAnimationOptions _keyboardAnimationOptions;
    
}
@end

@implementation CustomAlert

+ (instancetype)makeAlertWithCustomView:(UIView *)customView
                        leftButtonTitle:(NSString *)leftButtonTitle
                       rightButtonTitle:(NSString *)rightButtonTitle
                              leftBlock:(void (^)(void))leftBlock
                             rightBolck:(void (^)(void))rightBlock{
    CustomAlert *alert = [[CustomAlert alloc] initWithCustomView:customView leftButtonTitle:leftButtonTitle rightButtonTitle:rightButtonTitle leftBlock:leftBlock rightBolck:rightBlock];
    [alert show];
    return alert;
    
}

-(instancetype)initWithCustomView:(UIView *)customView
                  leftButtonTitle:(NSString *)leftButtonTitle
                 rightButtonTitle:(NSString *)rightButtonTitle
                        leftBlock:(void (^)(void))leftBlock
                       rightBolck:(void (^)(void))rightBlock{
    self = [super initWithTitle:@" " message:@" " cancelButtonTitle:leftButtonTitle otherButtonTitle:rightButtonTitle];
    if (self)
    {
        self.contentView  = customView;
        
        self.cancelButton.titleLabel.font = [UIFont systemFontOfSize:17];
        [self.cancelButton setTitleColor:TEXT_COLOR_1 forState:UIControlStateNormal];
        [self.otherButton setTitleColor:TOPCAIL_COLOR forState:UIControlStateNormal];
        
        UIImage *backImage = [LGImageManagerIO createImageWithColor:TEXT_COLOR_4];
        [self.cancelButton setBackgroundImage:backImage forState:UIControlStateHighlighted];
        [self.otherButton setBackgroundImage:backImage forState:UIControlStateHighlighted];
        
        self.backgroundColor = WHITE_COLOR;
        
        [self actionWithBlocksCancelButtonHandler:leftBlock
                               otherButtonHandler:rightBlock];
        [self addKeyboardNotice];
        
        
    }
    return self;
}

- (instancetype)initWithCustomView:(UIView *)customView{
    self = [super initWithTitle:@" " message:@" " cancelButtonTitle:@"" otherButtonTitle:@""];
    if (self)
    {
        _blankNDSemicircleView  = customView;
        
        [self addKeyboardNotice];
    }
    return self;
}

- (void)addKeyboardNotice
{
    [NS_NOTIFICATION_CENTER addObserver:self selector:@selector(chatKeyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

// 创建带定时器的弹窗
- (void)countDownSecond:(CGFloat)second timeOutBlock:(__TimeOutBlock)block
{
    self.timeOutBlock = block;
    _timer = [NSTimer scheduledTimerWithTimeInterval:second target:self selector:@selector(alertDismissAndTimerInvalidate) userInfo:nil repeats:NO];
}
- (void)alertDismissAndTimerInvalidate
{
    if (_timer != nil)
    {
        if (self != nil && self.superview != nil)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self dismiss];
            });
        }
        [_timer invalidate];
    }
    
}

#pragma mark 重写父类
//initWithNDSemicircleView 这个方法需要重写这个方法
- (void)calculateFrame
{
    if (_blankNDSemicircleView)
    {
        [self addSubview:_blankNDSemicircleView];
        [self bringSubviewToFront:_blankNDSemicircleView];
        
        self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, _blankNDSemicircleView.width, _blankNDSemicircleView.height);
    }
    else
    {
        [super calculateFrame];
    }
}

- (void)show{
    [super show];
    //键盘通知
    [self updateBlankCustomViewConstraints];
}

- (void)showInView:(UIView *)view
{
    [super showInView:view];
    _frame = self.frame;
    [self updateBlankCustomViewConstraints];
}

- (void)dismiss{
    [super dismiss];
    [self endEditing:YES];
    [_timer invalidate];
    _timer = nil;
    if (self.timeOutBlock)
    {
        self.timeOutBlock();
    }
}

//更新约束
- (void)updateBlankCustomViewConstraints
{
    if (_blankNDSemicircleView.superview == nil && !_blankNDSemicircleView)
    {
        [self addSubview:_blankNDSemicircleView];
        [self bringSubviewToFront:_blankNDSemicircleView];
    }
    else
    {
        [_blankNDSemicircleView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
        }];
    }
}


/**
 键盘通知
 */
- (void)chatKeyboardWillChangeFrame:(NSNotification *)notification
{
    NSDictionary *userInfo = notification.userInfo;
    CGRect endFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGRect beginFrame = [userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
    
    _keyboardAnimationDuration = duration;
    
    _keyboardAnimationOptions = (curve << 16 | UIViewAnimationOptionBeginFromCurrentState);
    
    [self _willShowKeyboardFromFrame:beginFrame toFrame:endFrame];
    
}

/**
 键盘的frame逻辑预处理
 */
- (void)_willShowKeyboardFromFrame:(CGRect)beginFrame toFrame:(CGRect)toFrame
{
    //排除一个错误的响应
    if ((beginFrame.origin.y == toFrame.origin.y) && beginFrame.origin.y == [[UIScreen mainScreen] bounds].size.height)
    {
        return;
    }
    
    if (beginFrame.origin.y == [[UIScreen mainScreen] bounds].size.height)
    {
        [self _willShowBottomHeight:toFrame.size.height];
    }
    else if (toFrame.origin.y == [[UIScreen mainScreen] bounds].size.height)
    {
        [self _willShowBottomHeight:0];
    }
    else
    {
        [self _willShowBottomHeight:toFrame.size.height];
    }
}
/**
 键盘弹起的操作函数 不带动画Block
 
 @param bottomHeight 弹起的高度
 */
- (void)_willShowBottomHeight:(CGFloat)bottomHeight
{
    CGFloat bottom =  SCREEN_HEIGHT - _frame.origin.y - _frame.size.height;
    CGFloat space = bottom - (bottomHeight + 16);
    [UIView animateWithDuration:_keyboardAnimationDuration delay:0.0f options:_keyboardAnimationOptions animations:^{

        if (space < 0.0)
        {
            self.transform = CGAffineTransformMakeTranslation(0, space);
        }
    } completion:^(BOOL finished) {
        
    }];
}


-(void)dealloc
{
    [NS_NOTIFICATION_CENTER removeObserver:self];
    NSLog(@"dealloc-%@",NSStringFromClass([self class]));
}

@end
